const { sys_log_model: SysLogModel } = require('../models');
const DateUtils = require('../utils/dateUtils');
const UAParser = require('ua-parser-js');
const geoip = require('geoip-lite');

const logMiddleware = async (req, res, next) => {
    const startTime = Date.now();

    // 解析 User-Agent
    const ua = new UAParser(req.headers['user-agent']);
    const browser = ua.getBrowser();
    const os = ua.getOS();

    // 解析 IP 地址和地理位置
    const xRealIp = req.headers['X-Real-IP'];
    //  真实ip 参考地址 https://cloud.tencent.com/developer/article/1908285
    // const aa: string = headers['HTTP_CLIENT_ip'];
    const xForwardedFor = req.headers['X-Forwarded-For'];
    const { remoteAddress } = req.connection || {};
    const ip = xRealIp || xForwardedFor || req.ip || remoteAddress;
    const geo = geoip.lookup(ip.replace('::ffff:', ''));

    try {
        // 等待请求处理完成
        await next();

        // 构建日志对象
        const logData = {
            module: req.baseUrl.replace('/', '') || 'root',
            requestMethod: req.method,
            requestParams: JSON.stringify({
                ...(Object.keys(req.query).length > 0 && { query: req.query }),
                ...(Object.keys(req.body).length > 0 && { body: req.body }),
                ...(Object.keys(req.params).length > 0 && { params: req.params })
            }),
            responseContent: '请求成功',
            content: `${req.method} ${req.originalUrl}请求成功`,
            requestUri: req.originalUrl,
            method: req.originalUrl,
            ip: ip,
            province: geo ? geo.region : '',
            city: geo ? geo.city : '',
            executionTime: Date.now() - startTime,
            browser: browser.name || '',
            browserVersion: browser.version || '',
            os: `${os.name} ${os.version}`,
            createBy: req.user ? req.user.id : null,
            createTime: new Date(),
            isDeleted: 0
        };

        // 异步保存日志
        await SysLogModel.create(logData);

    } catch (error) {
        // 计算执行时间
        const executionTime = Date.now() - startTime;

        // 构建错误日志对象
        const errorLogData = {
            module: req.baseUrl.replace('/', '') || 'root',
            requestMethod: req.method,
            requestParams: JSON.stringify({
                ...(Object.keys(req.query).length > 0 && { query: req.query }),
                ...(Object.keys(req.body).length > 0 && { body: req.body }),
                ...(Object.keys(req.params).length > 0 && { params: req.params })
            }),
            responseContent: error.message,
            content: `${req.method} ${req.originalUrl}请求失败：${error.message}`,
            requestUri: req.originalUrl,
            method: req.route ? req.route.path : '',
            ip: ip,
            province: geo ? geo.region : '',
            city: geo ? geo.city : '',
            executionTime: executionTime,
            browser: browser.name || '',
            browserVersion: browser.version || '',
            os: `${os.name} ${os.version}`,
            createBy: req.user ? req.user.id : null,
            createTime: DateUtils.getCurrentTime(),
            isDeleted: 0
        };

        // 异步保存错误日志
        await SysLogModel.create(errorLogData);

        // 继续抛出错误
        throw error;
    }
};

module.exports = logMiddleware;